package mgodb

import (
	"jgt-wallet/src/model"
	"jgt-wallet/src/schema"
	"jgt-wallet/src/service/mongo"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
)

// cLogManage 日志管理表名
const cLogManage = "oper_log"

// LogManage 日志管理
type LogManage struct {
	DB *mongo.DB
}

// Init 初始化
func (a *LogManage) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cLogManage, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id"},
			Unique: true,
		})
		c.EnsureIndexKey("type")
		c.EnsureIndexKey("level")
		return nil
	})

	var val model.ILogManage = a
	g.Provide(&inject.Object{Value: val, Name: "ILogManage"})
}

// QueryPage 查询分页数据
func (a *LogManage) QueryPage(params schema.LogManageQueryParam, pageIndex, pageSize uint) (int64, []*schema.LogManageQueryResult, error) {
	query := bson.M{}

	if v := params.Type; v != "" {
		query["type"] = v
	}

	if v := params.Level; v != "" {
		query["level"] = v
	}

	if v := params.Message; v != "" {
		query["message"] = bson.M{"$regex": v}
	}

	var total int64
	var items []*schema.LogManageQueryResult
	err := a.DB.C(cLogManage, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}

		return c.Find(query).Sort("-_id").Skip(int((pageIndex - 1) * pageSize)).Limit(int(pageSize)).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}
